#include"../source/server.hpp"
#include"../source/Socket.hpp"

void HandleClose(Channel *channel){
    std::cout<<"close:"<<channel->Fd()<<std::endl;
    channel->Remove();
    delete channel;
}

void HandleRead(Channel *channel){
    int fd = channel->Fd();
    char buf[1024] = {0};
    int ret = recv(fd,buf,1023,0);
    if(ret<0){
        lg(Error,"SOCKET RECV FAILED!");
        return;
    }
    channel->EnableWrite();//启动事件可写,发送数据,_events 会改变
    std::cout<<buf<<std::endl;
}

void HandleWrite(Channel *channel){
    int fd = channel->Fd();
    const char *data = "天气还不错！";//发送数据，固定数据
    int ret = send(fd,data,strlen(data),0); 
    if(ret<0){
        return HandleClose(channel);//发送失败，关闭连接，HandleWrite执行完后，还会处理默认事件，但是channel已经被删除  
    }
    channel->DisableWrite();//关闭事件可写  
}


void HandleError(Channel *channel){
    return HandleClose(channel);    
}

void HandleEvent(Channel *channel){
    std::cout<<"event:"<<channel->Fd()<<std::endl;
}

void Accepter(Poller *poller,Channel *lst_channel){
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL);
    if(newfd < 0){
        lg(Error,"ACCEPT FAILED!");
        return;
    }
    Channel * channel = new Channel(poller,newfd);//创建新的Channel
    channel->SetReadCallback(std::bind(HandleRead,channel));
    channel->SetWriteCallback(std::bind(HandleWrite,channel));
    channel->SetCloseCallback(std::bind(HandleClose,channel));
    channel->SetErrorCallback(std::bind(HandleError,channel)); 
    channel->SetEventCallback(std::bind(HandleEvent,channel));//
    channel -> EnableRead();//可读事件
}

int main(){ //先实现一个EventLoop,
    Socket TCP_Server;
    TCP_Server.CreateServer(8888);
    Poller _poller;
    Channel _channel(&_poller,TCP_Server.Fd());
    //创建channel,并添加监控?在哪里添加监控？
    _channel.SetReadCallback(std::bind(Accepter,&_poller,&_channel)); 
    _channel.EnableRead();    
    while(1){
        std::vector<Channel *> actives;
        _poller.Poll(&actives);
        for(auto &a:actives){
            a->HandleEvent();
        }
    }
    return 0;
}